#include "Common.h"
#include "MaterialManager.h"
#include "Material.h"
#include "Shader.h"
#include "ShapeHelper.h"


MaterialManager::MaterialManager()
	: mDefaultMatrial(NULL)
{
}

MaterialManager::~MaterialManager()
{
	RemoveAll();
}

Material* MaterialManager::Create(const std::string& name)
{
	if (GetByName(name) != NULL)
		return NULL;

	Material* material = new Material(name);
	mMaterials[name] = material;

	return material;
}

Material* MaterialManager::GetByName(const std::string& name)
{
	MaterialMap::iterator it = mMaterials.find(name);
	if (it != mMaterials.end())
		return it->second;
	return NULL;
}

bool MaterialManager::RemoveByName(const std::string& name)
{
	MaterialMap::iterator it = mMaterials.find(name);
	if (it == mMaterials.end())
		return false;

	delete it->second;
	mMaterials.erase(it);
	return true;
}

void MaterialManager::RemoveAll()
{
	for (MaterialMap::iterator it(mMaterials.begin()), end(mMaterials.end()); it != end; it++)
		delete it->second;
	mMaterials.clear();
}

void MaterialManager::LoadFromCache()
{
	const ShaderType::ShaderTypeList& shaderTypes = ShaderType::getShaderTypeList();
	for (ShaderType::ShaderTypeList::const_iterator it(shaderTypes.begin()), end(shaderTypes.end()); it != end; it++)
	{
	}
}

void MaterialManager::BuildReserveMaterial()
{
	// the default material, nothing to do.
	mDefaultMatrial = Create("DefaultMaterial");
	mDefaultMatrial->Compile();

	// the shape material.
	mShapeMaterial = ShapeHelper::BuildShapeMaterial("ShapeMaterial");
}